package com.amigo.online.provider.common.compare;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractBasicCompareService {

    // public void Compare(List<S>,);
    private static Logger logger = LoggerFactory.getLogger(AbstractBasicCompareService.class);

    public static boolean compareTwo(Object source, Object target) {
        if (source == null && target == null) {
            return true;
        }
        if (source == null && target != null) {
            return false;
        }
        if (source.equals(target)) {
            return true;
        }
        return false;
    }

    /**
     * @throws
     * @Title: compare
     * @Description: (按target 中的属性 ， 来比较source和target)
     * @param: @param source
     * @param: @param target
     * @param: @param resultMap
     * @param: @return
     * @return: boolean
     */
    public static void compare(Object source, Object target, Map<String, Object> resultMap) {
        Class<?> targetClass = target.getClass();
        Class<?> sourceClass = source.getClass();
        Field[] targetFields = targetClass.getDeclaredFields();
        Field[] sourceFields = sourceClass.getDeclaredFields();
        Map<String, Field> map = new HashMap<>(24);
        for (int j = 0; j < sourceFields.length; j++) {
            map.put(sourceFields[j].getName(), sourceFields[j]);
        }
        for (int i = 0; i < targetFields.length; i++) {
            targetFields[i].setAccessible(true);
            Field sourceField = map.get(targetFields[i].getName());
            sourceField.setAccessible(true);
            try {
                if (!AbstractBasicCompareService.compareTwo(targetFields[i].get(target), sourceField.get(source))) {
                    resultMap.put(sourceField.getName(), sourceField.get(source));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                logger.error(sourceClass.getName() + e);
            }
        }
    }
}
